<script setup>
/**
 * & 文件引入区域
 */
import { useI18n } from "vue-i18n";
import { onMounted, reactive, ref,watch  } from "vue";

import { itemStore } from "@/stores/item";
import { useUseStore } from "@/stores/user";
import { useIndexStore } from "@/stores/indexStore";

import { langList } from "@/data/langList";
import { countryList } from "@/data/countryList";

import { ToastFun } from "@/hook/toast";
import { OpenChildrenPage } from "@/hook/routerHandle";

import {
  getThirdDistrictList,
  getSecondDistrictList,
  getFourthDistrictList,
} from "@/server/api/BuyerData";
import { useRouter } from "vue-router";

/**
 * & 注册区
 */
const props = defineProps(["type", "isScaner", "regionChange",]);
const emit = defineEmits([
  "searchFun",
  "itemDataChangeFun",
  "shopDataChangeFun",
]);

/**
 * & 变量声明区
 */
const { locale } = useI18n();
let changeView = reactive({
  isLang: false, // 控制语言设置面板的显示隐藏
  isCountry: false, // 控制国家设置面板的显示隐藏
  isProvince: false, // 控制省份设置面板的显示隐藏
  isCity: false, // 控制城市设置面板的显示隐藏
  isRegion: false, // 控制区县设置面板的显示隐藏
});

let showBottom = ref(false); // 控制弹出层样式

let secDisList = ref(); // 二级行政区数据列表
let thdDisList = ref(); // 三级行政区数据列表
let fthDisList = ref(); // 四级行政区数据列表
let searchVl = ref(""); // 输入搜索的文本

let langCon = ref(null); // 控制选中的语言样式
let countryCon = ref(null); // 控制选中的国家样式
let provinceCon = ref(null); // 控制选中的省份样式
let cityCon = ref(null); // 控制选中的城市样式
let regionCon = ref(null); // 控制选中的区县样式

let countryImg = ref(""); // 显示的国旗

const router = useRouter();

/**
 * & 函数区
 */
// 返回方法
const backFun = () => {
  window.history.back();
  // router.back();
};

// 切换设置面板方法
const changeViewFun = (type) => {
  // 显示弹出层
  showBottom.value = true;

  // 通过遍历将所有的面板隐藏后，再将传入的type对应的面板显示
  for (const key in changeView) changeView[key] = false;
  changeView[type] = true;
};

// 搜索方法
const searchFun = () => {
  emit("searchFun", searchVl.value);
};

watch(searchVl, (newValue) => {
  if (newValue === "") {
    emit("searchFun", ""); 
  }
});

// 更改语言方法
const changeLang = (i) => {

  if (langList.value[i].lang == "ar") {
    useIndexStore().isRtl = true;
  } else {
    useIndexStore().isRtl = false;
  }

  // 切换语言
  locale.value = langList.value[i].lang;

  // 将下标存入数据管理库，持久化
  itemStore().langIndex = i;
  itemStore().lang = langList.value[i].lang;

  // 切换选中样式
  langCon.value = i;

  // 隐藏弹出层
  showBottom.value = false;
};

// 修改国家地区分类
const changeItemAddFun = (id, img) => {
  // 修改国家地区代码
  useUseStore().countryCode = id;

  console.log(id,"选择国家")
  // 切换国旗
  countryImg.value = img;

  // 判断是否在shop页面，从而请求二级三级行政区
  if (props.regionChange) {
    // 获取对应的二级行政区数据
    getSecDisListFun(id);

    regionCon.value = null;
  }

  // 避免重复点击发起请求
  if (countryCon.value != id) {
    countryCon.value = id;
    ToastFun("Loading", {});
    emit("itemDataChangeFun", id);

    // 弹出层隐藏
    showBottom.value = false;
  }
};

// 获取二级行政区域列表
const getSecDisListFun = async (id) => {
  ToastFun("Loading", { duration: 1000 });

  cityCon.value = null;

  let { data } = await getSecondDistrictList(id);

  if (data.code == 200) {
    ToastFun("close", {});
    secDisList.value = data.data;
    console.log("获取二级行政区域列表", secDisList.value);

    // 显示省份设置面板
    changeViewFun("isProvince");
  } else {
    ToastFun("", {});
  }
};

// 获取三级行政区域列表
const getThdDisListFun = async (id) => {
  provinceCon.value = id;
  ToastFun("Loading", { duration: 1000 });

  let { data } = await getThirdDistrictList(id); // 请求接口

  if (data.code == 200) {
    ToastFun("close", {});

    // 显示省份设置面板
    changeViewFun("isCity");
    thdDisList.value = data.data;
    console.log("获取三级行政区域列表", thdDisList.value);
  } else {
    ToastFun("", {});
  }
};

// 获取四级行政区域列表
const getFthDisListFun = async (id) => {
  cityCon.value = id;
  ToastFun("Loading", { duration: 1000 });
  let { data } = await getFourthDistrictList(id); // 请求接口

  if (data.code == 200) {
    ToastFun("close", {});

    // 显示省份设置面板
    changeViewFun("isRegion");
    fthDisList.value = data.data;
    console.log("获取四级行政区域列表", fthDisList.value);
  } else {
    ToastFun("", {});
  }
};

// 修改实体店地区方法
const changeShopAddFun = (id) => {
  console.log(countryCon.value, id);
  if (countryCon.value == "CN" && cityCon.value == null) {
    cityCon.value = id;
    getThdDisListFun(id);
  } else if (countryCon.value == "CN" && regionCon.value == null) {
    regionCon.value = id;
    getFthDisListFun(id);
  }
  // 避免重复发起请求
  else {
    cityCon.value = id;
    useUseStore().regionId = id;

    emit("shopDataChangeFun", id); // 修改实体店数据列表
    showBottom.value = false;
  }
};

// 追加country到countryList,如果用户有设置地区的话
// const addCountry = () => {
//   const area = ref(null)
//   area.value = useUseStore().userInfo.country;
//   // console.log(area.value);
//   let temp = ref("");
//   if (area.value !== null) {
//     for (let i = 0; i < countryList.length; i++) {
//       if (countryList[i].countryCode === area.value) {
//         temp.value = countryList[i];
//         // console.log(countryList[i], "11111111");
//       }
//     }
//     countryList.unshift(temp.value);
//   }
// }


onMounted(() => {
  // addCountry();
  countryCon.value = useUseStore().countryCode;
  // console.log("国家代码", useUseStore().countryCode);

  countryList.findIndex((item) => {
    if (useUseStore().countryCode == item.countryCode)
      countryImg.value = item.img;
  });


  // 获取默认语言下标
  let index = itemStore().langIndex;

  // 判断是否有选中语言的下标记录
  if (index == null) {
    index = langList.value.findIndex((item) => item.lang == locale.value);
  }

  langCon.value = index;
});
</script>

<template>
  <!-- 
    @searchFun：用于获取搜索框的内容
    isScaner: 是否显示扫描二维码
    type：样式类型
   -->
  <div class="topBarCom">
    <div :class="['topBar', useIndexStore().isRtl ? 'is_rtl' : '']">
      <img v-if="type == 2" src="/images/Home/backBtn.png" alt="" class="backBtn" @click="backFun" />

      <img src="/images/Me/scaner.png" alt="" v-if="isScaner" class="scaner"
        @click="OpenChildrenPage('/qrcodeScaner', { flag: true })" />

      <div class="search">
        <img alt="" src="/images/Home/搜索.png" :class="['logo', useIndexStore().isRtl ? 'is_rtl' : '']" />

        <input type="text" :placeholder="$t('input.placeholder')" v-model="searchVl" @keydown.enter="searchFun" />
      </div>

      <slot />

      <img class="logo" @click="changeViewFun('isLang')" src="/images/Home/iyanless.png" v-if="type == 1" />

      <img :src="`/images/countryImg/${countryImg ? countryImg : 'China.png'}`" @click="changeViewFun('isCountry')"
        v-if="type == 1" class="country" />
        
    </div>

    <!-- 语言和国家设置面板 -->
    <van-popup :style="{ height: '92%' }" v-model:show="showBottom" position="bottom" class="popup">
      <!-- 关闭弹窗按钮 -->
      <div class="btn">
        <img @click="showBottom = false" src="/images/Home/语言切换面板按钮.png" alt="" />
      </div>

      <div class="setUpView lang" v-if="changeView.isLang">
        <!-- <div class="select">
          <span>智能识别语言</span>
          <span class="selected">简体中文</span>
        </div> -->
        <div class="content">
          <div :class="['item', langCon == i ? 'con' : '']" v-for="(item, i) in langList" @click="changeLang(i)" :key="i">
            {{ item.title }}
          </div>
        </div>
      </div>

      <div class="setUpView country" v-if="changeView.isCountry">
        <!-- <div class="select">
          <span>智能识别国家</span>
          <span class="selected">加拿大</span>
        </div> -->
        <div class="content">
          <div :class="['item', countryCon == item.countryCode ? 'con' : '']"
            @click="changeItemAddFun(item.countryCode, item.img)" v-for="(item, i) in countryList" :key="i">

            <span>{{ item.countryEName }}</span>
            <img v-lazy="`/images/countryImg/${item.img}`" alt="" />
          </div>
        </div>
      </div>

      <div class="setUpView province" v-if="changeView.isProvince">
        <div class="content">
          <div :class="['item', provinceCon == item.countryId ? 'con' : '']" @click="changeShopAddFun(item.countryId)"
            v-for="(item, i) in secDisList" :key="i">
            <span>{{ item.name }}</span>
          </div>
        </div>
      </div>

      <div class="setUpView city" v-if="changeView.isCity">
        <div class="content">
          <div :class="['item', cityCon == item.countryId ? 'con' : '']" @click="changeShopAddFun(item.countryId)"
            v-for="(item, i) in thdDisList" :key="i">
            <span>{{ item.name }}</span>
          </div>
        </div>
      </div>

      <div class="setUpView region" v-if="changeView.isRegion">
        <div class="content">
          <div :class="['item', cityCon == item.countryId ? 'con' : '']" @click="changeShopAddFun(item.countryId)"
            v-for="(item, i) in fthDisList" :key="i">
            <span>{{ item.name }}</span>
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<style lang="scss" scoped>
.topBarCom {
  .topBar {
    padding: 20rem 16rem;
    display: flex;
    align-items: center;
    justify-content: space-between;

    &.is_rtl {
      flex-direction: row-reverse;
    }

    >.backBtn {
      width: 24rem;
    }

    >.scaner {
      width: 24rem;
    }

    >.logo {
      width: 20rem;
      height: 20rem;
      margin-right: 16rem;
    }

    >.more {
      width: 10rem;
      height: 6rem;
      margin-left: 8rem;
      margin-right: 10rem;

      &.btn2 {
        margin-left: 7rem;
        margin-right: 16rem;
      }
    }

    .search {
      flex: 1;
      margin: 0 10rem;

      height: 32rem;
      background: #f5f5f5;
      border-radius: 12rem;

      display: flex;
      align-items: center;

      >.logo {
        margin-left: 12rem;

        &.is_rtl {
          margin-left: 0;
          margin-right: 12rem;
        }
      }

      >input {
        border: 0;
        background: unset;
        outline: 0;
        text-indent: 5rem;
        font-size: 12rem;
      }
    }

    >.country {
      width: 34rem;
    }
  }

  :deep(.popup) {
    border-radius: 12rem 12rem 0rem 0rem;
    overflow-y: scroll;
    background: #f5f5f5;

    &::-webkit-scrollbar {
      display: none;
    }

    .btn {
      display: flex;
      justify-content: center;
      padding: 16rem 0 28rem;
      background: #f5f5f5;

      position: sticky;
      top: 0;
      z-index: 10;

      >img {
        width: 37rem;
        height: 8rem;
      }
    }

    .setUpView {
      z-index: 10;
      width: 100%;

      .select {
        padding: 12rem 0 12rem 12rem;
        background: #fff;

        display: flex;
        align-items: center;

        span {
          font-size: 14rem;
          line-height: 20rem;
          font-weight: 500;

          &.selected {
            font-size: 12rem;
            font-weight: 400;
            line-height: 16rem;
            margin-left: 12rem;
          }
        }
      }

      .content {
        font-size: 14rem;

        >.item {
          padding: 12rem;
          background: #fff;

          display: flex;
          align-items: center;
          justify-content: space-between;

          >img {
            width: 35rem;
          }

          &.con {
            background: #fbfbfb;
            font-weight: 700;
          }
        }
      }
    }
  }
}
</style>
